﻿// <copyright file="MapInfoFileTokeniser.cs" company="QUT">
//     Copyright (c) Ninety Nine Percent. All rights reserved.
// </copyright>

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Qut.GenerateKml.Data
{
    /// <summary>
    /// MapInfo File Tokeniser class.
    /// </summary>
    public class MapInfoFileTokeniser : MapInfoStringTokeniser
    {
        /// <summary>
        /// The stream reader.
        /// </summary>
        private StreamReader reader = null;

        /// <summary>
        /// The line number.
        /// </summary>
        private int lineNumber = 0;

        /// <summary>
        /// Initializes a new instance of the <see cref="MapInfoFileTokeniser"/> class.
        /// </summary>
        /// <param name="areader">A stream reader.</param>
        public MapInfoFileTokeniser(StreamReader areader)
            : base()
        {
            this.reader = areader;
        }

        /// <summary>
        /// Closes this instance.
        /// </summary>
        public void Close()
        {
            try
            {
                this.reader.Close();
                this.reader = null;
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// Reads the line.
        /// </summary>
        /// <returns>Returns bool indicating result.</returns>
        public override bool ReadLine()
        {
            string buffer = string.Empty;
            do
            {
                try
                {
                    buffer = this.reader.ReadLine();

                    if (buffer == null)
                    {
                        return this.ReadLine(string.Empty); // EOF
                    }
                }
                catch (Exception)
                {
                    return this.ReadLine(string.Empty);
                }

                this.lineNumber++;
                buffer = buffer.Trim();
            } 
            while (buffer.Length == 0);

            return this.ReadLine(buffer);
        }

        /// <summary>
        /// Gets the line number.
        /// </summary>
        /// <returns>Returns the line number.</returns>
        public int GetLineNumber()
        {
            return this.lineNumber;
        }
    }
}
